//Example 26

import java.io.*;
import java.net.*;

public class peer3{

    // Declaration section:
    // declare a server socket and a client socket for the server
    // declare an input and an output stream
    
    static  Socket clientSocket = null;
    static  ServerSocket serverSocket = null;
	public static int limit_conn = 100;
    // This chat server can accept up to 10 clients' connections

    static  clientThread t[] = new clientThread[limit_conn];
    
    public static void main(String args[]) {
		// The default port
		int port_number=2222;
		
		if (args.length < 1)
		{
			System.out.println("Usage: java peer3 \n"+"Now using port number="+port_number);
		}
		else
		{
			port_number=Integer.valueOf(args[0]).intValue();
		}
		
		// Initialization section:
		// Try to open a server socket on port port_number (default 2222)
		// Note that we can't choose a port less than 1023 if we are not
		// privileged users (root)

		try {
		serverSocket = new ServerSocket(port_number);
		}
		catch (IOException e)
		{System.out.println(e);}
		
		// Create a socket object from the ServerSocket to listen and accept 
		// connections.
		// Open input and output streams for this socket will be created in 
		// client's thread since every client is served by the server in
		// an individual thread
	
		while(true)
		{
			try
			{
				int i;
				clientSocket = serverSocket.accept();
				for(i=0; i<limit_conn && (t[i] !=null); ++i);
				if (i<limit_conn)
					(t[i] = new clientThread(clientSocket,t)).start();
			}
			catch (IOException e)
			{
				System.out.println(e);
			}
		}
    }
} 

// This client thread opens the input and the output streams for a particular client,
// ask the client's name, informs all the clients currently connected to the 
// server about the fact that a new client has joined the chat room, 
// and as long as it receive data, echos that data back to all other clients.
// When the client leaves the chat room this thread informs also all the
// clients about that and terminates. 

class clientThread extends Thread{
    
    DataInputStream is = null;
    PrintStream os = null;
    Socket clientSocket = null;       
    clientThread t[]; 
    
    public clientThread(Socket clientSocket, clientThread[] t){
		this.clientSocket=clientSocket;
        this.t=t;
    }
    
    public void run() 
    {
		String line;
        String name;
		try
		{
			int command;
			is = new DataInputStream(clientSocket.getInputStream());
			os = new PrintStream(clientSocket.getOutputStream());
			long waktu = System.currentTimeMillis(), waktu2;
			int length;
			String s;
			
			int count = 0;
			
			while ((waktu2 = System.currentTimeMillis()-waktu)<=120000)
			{
				waktu += waktu2;
				line = is.readLine();
				command = parse(line);
				length = line.length();
				if (command == 8) //kalo cancel, bingung ngapain dulu
				{
					s = line.substring(5,9);
					os.print("cancel, index = "+StrToInt(s));
					s = line.substring(9,13);
					os.print(", begin = "+StrToInt(s));
					s = line.substring(13,17);
					os.print(", length = "+StrToInt(s));
					System.out.println("a "+(++count));
				}
				else if (command == 7)
				{
					s = line.substring(5,9);
					os.print("piece, index = "+StrToInt(s));
					s = line.substring(9,13);
					os.print(", begin = "+StrToInt(s));
					s = line.substring(13,length);
					os.print(", block = "+StrToInt(s));
					System.out.println("b "+(++count));
				}
				else if (command == 6)
				{
					s = line.substring(5,9);
					os.print("request, index = "+StrToInt(s));
					s = line.substring(9,13);
					os.print(", begin = "+StrToInt(s));
					s = line.substring(13,length);
					os.print(", length = "+StrToInt(s));
					System.out.println("c "+(++count));
				}
				else if (command == 5)
				{
					s = line.substring(5,length);
					os.println("bitfield : "+StrToInt(s));
					System.out.println("d "+(++count));
				}
				else if (command == 4)
				{
					s = line.substring(5,length);
					os.println("punya piece indeks ke-"+StrToInt(s));
					System.out.println("e "+(++count));
				}
				//os.println("command = "+command);
				for(int i=0; i<peer3.limit_conn; i++)
					if (t[i]!=null)  t[i].os.println(", pesan yg dikirim : " + line);
				t[0].os.println("*** Bye");
			}
			os.println("waktu 2 = "+waktu2);
			// Clean up:
			// Set to null the current thread variable such that other client could
			// be accepted by the server

			for(int i=0; i<peer3.limit_conn; i++)
				if (t[i]==this)
					t[i]=null;
			
			// close the output stream
			// close the input stream
			// close the socket
			
			is.close();
			os.close();
			clientSocket.close();
		}
		catch(IOException e){};
    }
	
	private int StrToInt(String s)
	{
		int i = s.length(), j, hasil=0;
		for (j=0; j<i; ++j)
			hasil = hasil*256+(int)s.charAt(j);
		return hasil;
	}
	
	private int parse(String message)
	{
		if (message.startsWith("0000"))
		{
			return -1;
		}
		else if (message.startsWith("0001"))
		{
			return 5;
		}
		else if (message.startsWith("0005"))
		{
			if (message.charAt(4)=='4')
				return 4;
			else
				return 5;
		}
		else if (message.startsWith("0009"))
		{
			if (message.charAt(4)=='7')
				return 7;
			else
				return 5;
		}
		else if (message.startsWith("0013"))
		{
			if (message.charAt(4)=='5')
				return 5;
			else if (message.charAt(4)=='6')
				return 6;
			else if (message.charAt(4)=='7')
				return 7;
			else
				return 8;
		}
		else
		{
			if (message.charAt(4)=='5')
				return 5;
			else
				return 7;
		}
	}
}